<template>

  <div>
    <el-upload
      class="upload-demo"
      style="width:50%"
      action="#"
      :on-preview="preview"
      :on-change="changeFile"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :http-request="UploadFile"
      :disabled="isTrue"
    >
      <el-button :disabled="isTrue" size="small" type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>

<script>
import { UploadFile2 } from '@/api/user'
export default {
  props: {
    isTrue: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      imgUrl: '',
      fileList: [],
      currentFileUid: null
    }
  },
  computed: {
    fileComputed() {
      return this.fileList.length === 1
    }
  },
  methods: {
    // file是点击删除的文件
    handleRemove(file) {
      //   将原来的文件给排除掉了 剩下的就是最新的数组了
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    // 点击预览
    preview(file) {
      // // 这里应该弹出一个层 层里是点击的图片地址
      this.dowBtn(file)
    },
    async dowBtn(row) {
      await this.$confirm('确定要下载该文件吗？')
      const a = document.createElement('a') // 创建一个a标签
      a.href = row.url // 设置a标签的href属性为临时URL
      a.click() // 模拟点击a标签进行下载
      this.$message.success('下载成功！')
    },
    // 上传成功之后 还会进来 需要实现上传代码的逻辑 这里才会成功
    changeFile(file, fileList) {
      console.log(file)
      this.fileList = fileList.map(item => item)
    },
    // // 做文件上传的检查了
    beforeUpload(file) {
      //  检查大小
      const maxSize = 5 * 1024 * 1024
      if (maxSize < file.size) {
        this.$message.error(this.$t('prompt.imgSize'))
        return false
      }
      this.currentFileUid = file.uid
      return true
    },
    // 上传
    async UploadFile(params) {
      const formData = new FormData()// 定义新的formData
      // 为formData赋值
      formData.append('file', params.file)
      formData.append('user', params.file.name)
      console.log(params.file.name)
      // 发起上传请求
      const file = await UploadFile2(formData)
      // 循环数组，为对应的filelist中的url替换
      this.fileList = this.fileList.map(item => {
        if (item.uid === this.currentFileUid) {
          return { url: file.file, upload: true, name: file.name }
        }
        return item
      })
    }
  }
}
</script>

<style>
    .disabled .el-upload--picture-card{
        display: none;
    }
    .showImg{
        width: 400px;
    }
</style>
